
import Vue from 'vue'
// import setting from '@/config/setting'
import Router from '@/router'
import Cache from 'storejs'
import {routeIndexConf} from '@/config/route'
// import 'whatwg-fetch'
import _ from 'lodash'
// import { UploaderBuilder } from 'qiniu4js'
// import Weditor from '@/lib/wangEditor'
const THIS = new Vue()
const Helper = {
  nativeShimBarHeight() {
    const BUILD = false
    return process.env.APP_MODULE === 'native' ? (Helper.isAndroid() ? (BUILD ? '25px' : '0px') : '20px') : '0px'
  },
  nativeShimCombineHeight(height) {
    return height ? `-webkit-calc( ${height} + ${Helper.nativeShimBarHeight()} )` : '0px'
  },
  nativeShimStyle(height = '0px') {
    return {
      paddingTop: Helper.nativeShimBarHeight(),
      height: Helper.nativeShimCombineHeight(height),
    }
  },
  isTest() {
    return process.env.NODE_ENV === 'development'
  },
  preSetParams(params) {
    let newData = {}
    for (let i in params) {
      if (params[i] !== null && params[i] !== undefined && params[i] !== '') {
        newData[i] = _.trim(params[i])
      }
    }
    return newData
  },
  ajax({ params = {}, method = 'POST', url, isFile = false }) {
    if (!url) throw new Error('Ajax error,without url!')
    let httpConf = {
      method,
      url,
      params: method === 'GET' ? params : {},
      body: isFile ? params : (method === 'POST' ? JSON.stringify(params) : {}),
      emulateHTTP: true,
      headers: {
        UUID: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzYWx0IjoiaW1Vc0RtRXVWRGhtZ1BqUkV6S08iLCJpZCI6IjM2IiwiaWF0IjoxNTI5NDY3MTA3fQ.NEg5u3EePep7iCbAhCNISBuwtl2g3UwkhJlFOYLNM4o',
        env: 'native',
      },
    }
    return new Promise((resolve, reject) => {
      THIS.$http(httpConf).then(
        ({ bodyText = '{}' }) => {
          let data = JSON.parse(bodyText)
          if (data.code === '401') {
            // Router.push({ name: 'Login' })
            // THIS.$Helper.emitAction('toast', {
            //   text: data.msg || '登录信息有误',
            // })
          } else {
            resolve(data)
          }
        },
        (e) => {
          reject(e)
        },
      ).catch(e => {
        reject(e)
      })
    })
  },
  persistence(n) {
    let count = 0
    const multiple = (arr) => {
      if (!this.isType(arr, [])) throw new Error('[multiple error]: expect a array!')
      let sum = 1
      arr.map(item => {
        sum = sum * parseInt(item)
      })
      return sum
    }
    const fn = (num) => {
      if (!(this.isType(num, '') || this.isType(num, 1))) throw new Error('[persistence error]: expect a string or a number!')
      const str = num.toString()
      if (str.indexOf('.') !== -1) throw new Error('[persistence error]: expect a integer!')
      if (str.length < 2) return 
      fn(multiple(str.split('')))
      count ++
    }
    fn(n)
    return count || 1
  },
  fetch(params) {
    return Helper.ajax(params)
  },
  formatTime(time) {
    let timeBetween = (new Date().getTime() - new Date(time.replace(/-/g, '/')).getTime()) / 1000      // 秒
    let returnData
    if (timeBetween < 15) {
      returnData = '刚刚'
    } else if (timeBetween >= 15 && timeBetween < 60) {
      returnData = parseInt(timeBetween) + '秒前'
    } else if (timeBetween >= 60 && timeBetween < 3600) {
      returnData = parseInt(timeBetween / 60) + '分钟前'
    } else if (timeBetween >= 3600 && timeBetween < 86400) {
      returnData = parseInt(timeBetween / 3600) + '小时前'
    } else if (timeBetween >= 86400 && timeBetween < 2592000) {
      returnData = parseInt(timeBetween / 86400) + '天前'
    } else if (timeBetween >= 2592000 && timeBetween < 31104000) {
      returnData = parseInt(timeBetween / 2592000) + '月前'
    } else if (timeBetween > 31104000) {
      returnData = time
    }
    return returnData
  },
  getCache(key) {
    return Cache.get(key)
  },
  setCache(key, data, long = 24 * 60 * 60) {  // save 1 day
    Cache.set(key, data, Helper.getTime() + long)
  },
  clearCache() {
    Cache.clear()
  },
  emitAction(type, data) {
    THIS.$emit(type, data)
  },
  onAction(type, callback) {
    THIS.$on(type, callback)
  },
  pushRoute(params) {
    params = typeof params === 'object' ? params : { name: params }
    Router.push(params)
  },
  getTime() {
    return new Date().getTime()
  },
  testParamsComplete({ params = {}, except = [], contain = [] }) {
    let obj = !_.isEmpty(contain) ? contain : params
    let emptyArr = []
    let isEmpty = (o) => {
      return (typeof o === 'object' && _.isEmpty(o)) || (typeof o === 'string' && _.trim(o) === '') || _.isUndefined(o)
    }
    for (let i in obj) {
      let key = _.isEmpty(contain) ? i : obj[i]
      let item = params[key]
      if (isEmpty(item) && except.indexOf(key) === -1) emptyArr.push(key)
    }
    return emptyArr
  },
  getUrlParams(key) {
    let href = window.location.href
    // let pramsString = href.substring(href.indexOf('?') + 1, href.indexOf('#'))
    let wIndex = _.lastIndexOf(href.split(''), '?')
    // console.log(wIndex)
    let pramsString = wIndex !== -1 ? href.substr(wIndex + 1) : ''
    let paramsArr = pramsString ? pramsString.split('&') : []
    let returnData = {}
    paramsArr.map((item) => {
      let arr = item.split('=')
      returnData[arr[0]] = arr[1]
    })
    return returnData
  },
  getUrlParamsByKey(key) {
    let params = Helper.getUrlParams()
    return params[key] || null
  },
  isArray: (obj) => {
    return Object.prototype.toString.call(obj) === '[object Array]'
  },
  isNumber: (value, isPlus = false) => {
    return isPlus ? /^\d.?\d+$/.test(value) : /^-?\d.?\d+$/.test(value)
  },
  isType(obj1, obj2) {
    return Object.prototype.toString.call(obj1) === Object.prototype.toString.call(obj2)
  },
  isAndroid() {
    let u = navigator.userAgent
    return u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  },
  isPc() {
    const userAgentInfo = navigator.userAgent
    const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'iPad', 'iPod']
    let flag = true
    for (let v = 0; v < Agents.length; v++) {
      if (userAgentInfo.indexOf(Agents[v]) > 0) {
        flag = false
        break
      }
    }
    return flag
  },
  getData(ob, str) {       // only object
    if (!this.isType(ob, {})) {
      return undefined
    }
    if (!this.isType(str, '')) {
      return undefined
    }
    let getParams = (obj, arr) => {
      if (this.isType(obj[arr[0]], undefined) || this.isType(obj[arr[0]], null)) {
        return undefined
      } else {
        if (arr.length > 1) {
          let key = arr.shift()
          let s = obj[key]
          return getParams(s, arr)
        } else {
          return obj[arr[0]]
        }
      }
    }
    return getParams(ob, str.replace(/\[\d+\]/g, s => `.${s.substr(1, s.length - 2)}`).split('.'))
  },
  initUploadImage(btnId, success = () => {}, key, type = 'image') {
    // if has cookie
    let savedCookie = JSON.parse(Helper.getCache(`${type}TokenCookie`) || '{}').cookie
    if (savedCookie) {
      this.createUpload({
        ...savedCookie,
        btnId,
        success,
        key,
        type,
      })
      return
    }
    // get upliod token and url
    Helper.ajax({
      url: 'WeOpen.Upload',
      method: 'GET',
    }).then(({data}) => {
      this.uptokenData = data.token
      this.createUpload({
        token: data.token,
        btnId,
        success,
        key,
        type,
      })
      // save token to cache
      Helper.setCache(`${type}TokenCookie`, { cookie: data })
    })
  },
  // createUpload({ btnId, token, cdnUrl, type = 'image', success = () => { console.log('withOut callback Fn!') }, key = `defaultImageKey_${Helper.getTime()}` }) {
  //   cdnUrl = cdnUrl || setting['cdn']
  //   let accept = {
  //     'image': ['image/*'],
  //     'video': ['video/*'],
  //   }[type]
  //   // 创建上传对象
  //   new UploaderBuilder()
  //   .debug(true)
  //   .button(btnId)
  //   .domain({http: 'http://up-z2.qiniu.com'})
  //   .retry(5)
  //   .chunk(true)
  //   .scale([1000, 0])
  //   .auto(true)
  //   .multiple(true)
  //   .accept(accept)
  //   .tokenShare(true)
  //   .tokenFunc((setToken, task) => {
  //     setToken(token)
  //   })
  //   .listener({
  //     onReady(tasks) {
  //       // console.log('onReady', tasks)
  //     },
  //     onStart(tasks) {
  //       dispatch(`loading/update`, {
  //         status: true,
  //         text: `开始上传...`,
  //       })
  //     },
  //     onTaskGetKey: () => {
  //       return key
  //     },
  //     onTaskProgress: (task) => {
  //       dispatch('loading/update', {
  //         status: true,
  //         text: `正在上传, 进度${task.progress}%`,
  //       })
  //     },
  //     onTaskSuccess: (task) => {
  //       success(cdnUrl + '/' + task.result.key)
  //     },
  //     onFinish(tasks) {
  //       dispatch(`loading/update`, {
  //         status: false,
  //       })
  //     },
  //   })
  //   .build()
  // },
  // initEditor(editorSelector) {
  //   let editor = new Weditor(editorSelector)
  //   editor.customConfig.qiniu = true
  //   editor.customConfig.zIndex = 10
  //   editor.customConfig.menus = [
  //     'head',  // 标题
  //     'bold',  // 粗体
  //     'italic',  // 斜体
  //     'underline',  // 下划线
  //     'strikeThrough',  // 删除线
  //     'foreColor',  // 文字颜色
  //     'backColor',  // 背景颜色
  //     'link',  // 插入链接
  //     // 'list',  // 列表
  //     'justify',  // 对齐方式
  //     'quote',  // 引用
  //     // 'emoticon',  // 表情
  //     'image',  // 插入图片
  //     'table',  // 表格
  //     'video',  // 插入视频
  //     'code',  // 插入代码
  //     'undo',  // 撤销
  //     'redo',  // 重复
  //   ]
  //   editor.customConfig.onchange = html => {
  //     Helper.emitAction('editorchange', html)
  //   }
  //   editor.create()
  //   document.querySelector('.w-e-text-container').style.height = '60vh'
  //   Helper.initUploadImage(
  //     editor.imgMenuId,
  //     (data) => {
  //       editor.cmd.do('insertHtml', '<img src="' + data + '" style="max-width:100%;"/>')
  //     },
  //     `imageUploadBtnId_${Helper.getTime()}_${Math.random() * 10000}`
  //   )
  //   // 创建编辑器
  //   return editor
  // },
  assignObjParams(obj, paramsNames = [], removeEmpty = false) {
    if (!Helper.isType(paramsNames, [])) throw new Error('[assignObjParams error]: paramsNames must be a array!')
    if (!Helper.isType(obj, {})) throw new Error('[assignObjParams error]: obj must be a object!')
    let ob = {}
    paramsNames.map(item => {
      if (Helper.isType(item, '')) {
        let value = obj[item]
        ob[item] = (value === '' || value === null || value === undefined) && removeEmpty ? undefined : value
      }
    })
    return ob
  },
  getObjParams({ obj = {}, params = [], exceptEmptyParams = [], emptyType = [undefined, null, '', 0], emptyReplace = undefined }) {
    // test params type
    if (!Helper.isType(obj, {})) throw new Error('[assignObjParams error]: obj must be a object!')
    if (!Helper.isType(params, [])) throw new Error('[assignObjParams error]: params must be a array!')
    if (!Helper.isType(exceptEmptyParams, [])) throw new Error('[assignObjParams error]: exceptEmptyParams must be a array!')
    if (!Helper.isType(emptyType, [])) throw new Error('[assignObjParams error]: emptyType must be a array!')
    let ob = {}
    params.map(item => {
      if (Helper.isType(item, '')) {
        let value = obj[item]
        if (exceptEmptyParams.indexOf(item) === -1 && emptyType.indexOf(value) !== -1) value = emptyReplace
        ob[item] = value
      }
    })
    return ob
  },
  requireAll(requireContext) {
    const ret = {}
    const getFileName = arr => arr.length > 2 && arr[arr.length - 1] === 'index.vue' ? arr[arr.length - 2] : (arr[arr.length - 1] !== '__index__.vue' ? arr[arr.length - 1].split('.')[0] : null)
    requireContext.keys().forEach(k => {
      let fileName = getFileName(k.split('/'))
      if (fileName && ['index'].indexOf(fileName)===-1) ret[fileName] = requireContext(k)
    })
    return ret
  },
  setDocumentTiTle(title) {
    let i = document.createElement('iframe')
    i.src = '../favicon.ico'
    i.style.display = 'none'
    i.onload = () => {
      setTimeout(() => {
        i.remove()
      }, 9)
    }
    document.title = title
    document.body.appendChild(i)
  },
  jumpPage(params, that) {
    params = typeof params === 'object' ? params : { name: params }
    // console.log(THIS)
    if (Helper.getRouteIndex(that.$route.name) === Helper.getRouteIndex(params.name) || Helper.getRouteIndex(params.name) === 0) {
      Router.replace(params)
    } else {
      Router.push(params)
    }
  },
  jumpBack() {
    Router.go(-1)
  },
  getRouteIndex(name) {
    let key = null
    for (let i in routeIndexConf) {
      let item = routeIndexConf[i]
      if (_.indexOf(item, name) !== -1) {
        key = parseInt(i)
      }
    }
    return key
  },
  dom: {
    addClass: (obj, className) => {
      if (obj.className === ``) {
        obj.className = className
      } else {
        if (Helper.dom.classIndexOf(obj, className) === -1) {
          obj.className += ` ` + className
        }
      }
    },
    classIndexOf: (obj, v) => {
      const arrClassName = obj.className.split(` `)
      for (let i = 0; i < arrClassName.length; i++) {
        if (arrClassName[i] === v) return i
      }
      return -1
    },
  },
  overScroll(el) {
    // this.dom.addClass(el, 'mescroll')
    el.addEventListener('touchstart', () => {
      let top = el.scrollTop
      let totalScroll = el.scrollHeight
      let currentScroll = top + el.offsetHeight
      if (top === 0) {
        el.scrollTop = 1
      } else if (currentScroll === totalScroll) {
        el.scrollTop = top - 1
      }
    })
    el.addEventListener('touchmove', (evt) => {
      if (el.offsetHeight < el.scrollHeight) evt._isScroller = true
    })
  },
  noScroll(el) {
    el.addEventListener('touchmove', (evt) => {
      evt.preventDefault()
    })
  },
  dateDiff(startDateString, endDateString) {
    let separator = `-`
    let startDates = startDateString.split(separator)
    let endDates = endDateString.split(separator)
    let startDate = new Date(startDates[0], startDates[1] - 1, startDates[2])
    let endDate = new Date(endDates[0], endDates[1] - 1, endDates[2])
    return parseInt((endDate - startDate) / 1000 / 60 / 60 / 24)
  },
  getDate(time = new Date(), separator = '-') {
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let day = time.getDate()
    return `${year}${separator}${month < 10 ? '0' + month : month}${separator}${day < 10 ? '0' + day : day}`
  },
  safeGetTime(str) {
    return new Date(Date.parse(str.replace(/-/g, '/'))).getTime()
  },
}
export default Helper
